# agentesF version 0.1, Copyright 2008 __MyCompanyName__.

use strict;
use warnings;
use dataSource;

package agentesFWindowController;

use CamelBones qw(:All);
use Data::Dumper;
use Database::Main;

class agentesFWindowController {
    'super' => 'NSObject',
    'properties' => [
                        'windowController','tableView','textField'                    
		],
};

sub init : Selector(init) ReturnType(@) {
    my ($self) = @_;
    
    $self->setWindowController(
            NSWindowController->alloc()->initWithWindowNibName_owner("MainWindow", $self));
    $self->windowController()->window();
		my $ds= dataSource->alloc()->init();
		$self->tableView()->setDataSource($ds);
		#print Dumper($self->launchPdfCreator());
		$self->{myDataSource}=$ds;
    return $self;
}

sub search: Selector(search:) IBAction {
	my ($self) = @_;
	#print "Buscamos\n";
	print $self->textField()->stringValue;
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $rs = $schema->resultset('Places')->find ({lugar => $self->textField()->stringValue});
	#print Dumper($rs);
	if (defined($rs)){
		PdfCreator($self,$rs);
	}else{
		use wikipedia;
		use weatherfinder;
		my %data = search_wiki($self->textField()->stringValue);
		print Dumper(%data);
		print "antes de insertar place\n";
		
		my $id = inserta_place($self->textField()->stringValue,$data{prov});
		print "antes de insertar wiki\n";
		inserta_wiki($id,$data{texto});
		print "antes de llamar a insertar enlace\n";
		inserta_enlace($id,$data{links});
		print "antes de llamar a buscar weather\n";
		my $weather=buscar($id,$data{prov});
		print "antes de insertar weather\n";
		if ($weather){
			inserta_weather($id,$weather);
		}
		print "antes de insertar imagenes\n";
		inserta_imagenes($id,$data{imagen});
		$rs = $schema->resultset('Places')->find ({lugar => $self->textField()->stringValue});
		PdfCreator($self,$rs);
	}
}

sub PdfCreator {
	my $self = shift;
	my $rsname = shift;
	use Data::Dumper;
	#print $self->tableView()->selectedRow;
	my %salida;
	my @rs;
	my $data;
	if (!$rsname){
		#print "\n\nDesde boton de crear pdf\n\n";
		@rs = list_all_places();
		$data = $rs[$self->tableView()->selectedRow];
	}else{
		#print "\n\nPasando datos \n\n";
		$data = $rsname;
	}
	
	############### Weather ####################
	my $weather = busca_weather($data->id);
	if (!defined($weather)){
		use weatherfinder;
		$weather = buscar($data->demas,$data->lugar);
		if (defined($weather)){
			inserta_weather($data->id,$weather);
		}
	}
	print Dumper($weather);
	############################################
	
	############### Wikipedia #################

	my $wiki = busca_wiki($data->id);
	print Dumper($wiki);
	if (!defined($wiki)){
		%salida = search_wiki($data->lugar);
		if (defined($salida{texto})){
			inserta_wiki($data->id,$salida{texto});
			$wiki = $salida{texto};
		}
	}
	print Dumper($wiki);
	##########################################
	
	############### Enlaces ##################
	my $enlaces = busca_enlaces($data->id);
	if (!defined($enlaces)){
		if (%salida){
			if (defined($salida{links})){
				inserta_enlace($data->id,$salida{links});
				$enlaces = $salida{links};
			}
		}else{
			%salida = search_wiki($data->lugar);
			if (defined($salida{links})){
				inserta_enlace($data->id,$salida{links});
				$enlaces = $salida{links};
			}
		}
	}
	print Dumper($enlaces);
	############# Imagenes  #################
	my $imagenes = busca_imagenes($data->id);
	
	if (!defined($imagenes)){
		if (%salida){
			if (defined($salida{imagen})){
				inserta_imagenes($data->id,$salida{imagen});
				$imagenes = $salida{imagen};
			}
		}else{
			%salida = search_wiki($data->lugar);
			if (defined($salida{imagen})){
				inserta_imagenes($data->id,$salida{imagen});
				$imagenes = $salida{imagen};
			}
		}
	}
	print Dumper($imagenes);
	
	#print "Vamos a crear el PDF\n";
	##########################################
	
	use agentePDFLatex;
	
	createPDF($data->lugar,$weather,$data->demas,$wiki,$enlaces,$imagenes);
}


# Handle the launchPdfCreator: action
sub launchPdfCreator : Selector(launchPdfCreator:) IBAction {
	my ($self) = shift;
	PdfCreator($self);
}


#Lista todos los lugares devolviendo un array con ellos

sub list_all_places {
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my @rs = $schema->resultset('Places')->all();
	
	return @rs
}
#devuelve el dato wiki que corresponda

sub busca_wiki {
	my $lugar = shift;
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $rs = $schema->resultset('Wiki')->search_rs ({places => $lugar});
	
	my $wiki = $rs->first;
	if (defined($wiki)){
		return $wiki->texto; 
	}else{
		return undef;
	}
}
#devuelve un array con los enlaces de un dato

sub busca_enlaces {
	my $lugar = shift;
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $rs = $schema->resultset('Enlaces')->search_rs ({places => $lugar});
	
	my @enlaces;# = map {$_->link} @rs;
	my $temp = $rs->first;
	if (defined($temp)){
		while ($temp) {
			push (@enlaces, $temp->link);
			$temp = $rs->next;
		} 
		return \@enlaces;
	}else{
		return undef;
	}
}
#devuelve el dato tiempo que corresponda

sub busca_weather {
	my $lugar = shift or die "No se ha dado clave de busqueda";
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $rs = $schema->resultset('Weather')->search_rs ({places => $lugar});

	
	my $weather= $rs->first;
	if (defined($weather)){
		my %salida = (HOY => $weather->hoy, MANA => $weather->manana, PM => $weather->pasado);
		#print Dumper(%salida), "\n";
		return \%salida;
	}else{
		return undef;
	}
}
#inserta elementos en places
sub inserta_place {
	
	my $lugar = shift;
	print "lugar = ".$lugar."\n";
	my $demas = shift || undef;
	print "demas = ".$demas."\n";
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	#my $rs = $schema->resultset('Places')->find ({lugar => $lugar});
	#my $result = $rs->first;
	#print Dumper($result);
	
	#if (!defined($result)){
		my $id = $schema->resultset('Places')->create ({
			lugar=>$lugar,
			demas=>$demas
		});
		return $id;
	#	}else{
	#		$result->update({
	#		lugar=>$lugar,
	#		demas=>$demas
	#	});
	#	return $rs->id;
	#}
	
}

#inserta elementos en wiki
sub inserta_wiki {
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $lugar = shift;
	my $text = shift || "null";
	
	my $rs = $schema->resultset('Wiki')->search_rs ({places => $lugar});
	my $result = $rs->first;
	if (!defined($result)){
		$schema->resultset('Wiki')->create ({
			places=>$lugar,
			texto=>$text
		});
	}else{
		$result->update({
			places=>$lugar,
			texto=>$text
		});
	}
	
}

#inserta enlaces en enlace
sub inserta_enlace {
	
	my $lugar = shift;
	my $links = shift;
  my $schema = Database::Main->connect('dbi:SQLite:datos.db');       
	my $rs = $schema->resultset('Enlaces')->search_rs ({places => $lugar});
	my $result = $rs->first;
	if (!defined($result)){
		foreach my $link (@{$links}) {
			$schema->resultset('Enlaces')->create ({
				places=>$lugar,
				link=>$link
			});
			#print "$lugar $link\n";	
		}
	}else{
		foreach my $link (@{$links}) {
			$result->update({
				places=>$lugar,
				link=>$link
			});
		}
	}
	
}
#inserta elementos en wiki
sub inserta_weather {
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $lugar = shift or die "No se ha dado clave de busqueda";
	my $weather =shift;
	#my %weather = %{@temp};
	#print Dumper($temp{HOY});
	my $rs = $schema->resultset('Weather')->search_rs ({places => $lugar});
	my $result = $rs->first;
	if (!defined($result)){
		$schema->resultset('Weather')->find_or_create ({
			places=> $lugar,
			hoy => $weather->{HOY},
			manana => $weather->{MANA},
			pasado => $weather->{PM}
		});
	}else{
		$result->update({
			places=> $lugar,
			hoy => $weather->{HOY},
			manana => $weather->{MANA},
			pasado => $weather->{PM}
		});
	}
	
}
#inserta las imagenes
sub inserta_imagenes {
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $lugar = shift;
	my $imagenes = shift;
	
	my $rs = $schema->resultset('Imagenes')->search_rs ({places => $lugar}); 
	my $result = $rs->first;
	if (!defined($result)) {
	
		foreach my $imagen (@{$imagenes}) {
			$schema->resultset('Imagenes')->create ({
				places=>$lugar,
				imagen=>$imagen
			});
		}
			#print "$lugar $link\n";	
	}else{
		foreach my $imagen (@{$imagenes}) {
			$result->update({
				places=>$lugar,
				imagen=>$imagen
			});
		}
	}
	
}
#devuelve un array con las imagenes de un dato

sub busca_imagenes {
	my $lugar = shift;
	my $schema = Database::Main->connect('dbi:SQLite:datos.db');
	my $rs = $schema->resultset('Imagenes')->search_rs ({places => $lugar});
	
	my @enlaces;# = map {$_->link} @rs;
	my $temp = $rs->first;
	if (defined($temp)){
		while ($temp) {
			push (@enlaces, $temp->imagen);
			$temp = $rs->next
		} 
		return \@enlaces;
	}else{
		return undef;
	}
}

1;
